<template>
  <a-spin :spinning="confirmLoading">
    <!-- :disabled="disabled" -->
    <JFormContainer>
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="AmazonTaskProductForm">
          <a-row>
            <a-col :span="24">
              <a-form-item label="商品名称" v-bind="validateInfos.title" id="AmazonTaskProductForm-title" name="title">
                <a-input v-model:value="formData.title" placeholder="请输入商品名称"  :allow-clear="!disabled" ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="图片"  v-bind="validateInfos.productImage"  id="AmazonTaskProductForm-productImage" name="productImage">
                <JImageUpload :fileMax="0" :value="computedProductImage" @change="imageChange"></JImageUpload>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="sku" v-bind="validateInfos.sku" id="AmazonTaskProductForm-sku" name="sku">
                <a-input v-model:value="formData.sku" placeholder="请输入sku"  :allow-clear="!disabled" ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="品牌" v-bind="validateInfos.brand" id="AmazonTaskProductForm-brand" name="brand">
                <a-input v-model:value="formData.brand" placeholder="请输入品牌"  :allow-clear="!disabled" ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="最低价" v-bind="validateInfos.standardPrice" id="AmazonTaskProductForm-standardPrice" name="standardPrice">
                <a-input v-model:value="formData.standardPrice" placeholder="请输入最低价"  :allow-clear="!disabled" ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="运费" v-bind="validateInfos.yunfei" id="AmazonTaskProductForm-yunfei" name="yunfei">
                <a-input v-model:value="formData.yunfei" placeholder="请输入运费"  :allow-clear="!disabled" ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="最高价" v-bind="validateInfos.highPrice" id="AmazonTaskProductForm-highPrice" name="highPrice">
                <a-input v-model:value="formData.highPrice" placeholder="请输入最高价"  :allow-clear="!disabled" ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="库存" v-bind="validateInfos.quantity" id="AmazonTaskProductForm-quantity" name="quantity">
                <a-input v-model:value="formData.quantity" placeholder="请输入库存"  :allow-clear="!disabled" ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="上架时间" v-bind="validateInfos.startDate" id="AmazonTaskProductForm-startDate" name="startDate">
                <a-input v-model:value="formData.startDate" placeholder="请输入上架时间"  :allow-clear="!disabled" ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="货币单位" v-bind="validateInfos.currency" id="AmazonTaskProductForm-currency" name="currency">
                <a-input v-model:value="formData.currency" placeholder="请输入货币单位"  :allow-clear="!disabled" ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="卖家完整地址" v-bind="validateInfos.sellerAddress" id="AmazonTaskProductForm-sellerAddress" name="sellerAddress">
                <a-input v-model:value="formData.sellerAddress" placeholder="请输入卖家完整地址"  :allow-clear="!disabled" ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="采集任务id" v-bind="validateInfos.taskId" id="AmazonTaskProductForm-taskId" name="taskId">
                <a-input v-model:value="formData.taskId" placeholder="请输入采集任务id"  :allow-clear="!disabled" ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="分类字符串" v-bind="validateInfos.cateStr" id="AmazonTaskProductForm-cateStr" name="cateStr">
                <a-input v-model:value="formData.cateStr" placeholder="" ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="asin码" v-bind="validateInfos.asin" id="AmazonTaskProductForm-asin" name="asin">
                <a-input v-model:value="formData.asin" placeholder="" ></a-input>
              </a-form-item>
            </a-col>
            <template v-if="disabled">
              <a-col :span="24">
                <a-form-item label="五点描述">
                  <a-textarea :rows="6" v-model:value="point" placeholder="" ></a-textarea>
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item label="长描述" v-bind="validateInfos.description" id="AmazonTaskProductForm-description" name="description">
                  <a-textarea :rows="10" v-model:value="description" placeholder="" ></a-textarea>
                  <!-- <JEditor v-model:value="formData.description" placeholder="" /> -->
                </a-form-item>
              </a-col>
            </template>
            <a-col :span="24">
              <a-form-item label="原链接" v-bind="validateInfos.purchase" id="AmazonTaskProductForm-purchase" name="purchase">
                <div style="display: flex;align-items: center;">
                  <a-input v-model:value="formData.purchase" placeholder="" style="flex: 1;"></a-input>
                  <a :href="formData.purchase" target="_blank" style="margin-left: 10px;">跳转网页</a>
                </div>
              </a-form-item>
            </a-col>
            <!-- <a-col :span="24">
                <a-form-item label="变体尺寸" v-bind="validateInfos.size" id="AmazonTaskProductForm-size" name="size">
                  <a-input v-model:value="formData.size" placeholder="" ></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item label="变体颜色" v-bind="validateInfos.color" id="AmazonTaskProductForm-color" name="color">
                  <a-input v-model:value="formData.color" placeholder="" ></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item label="变体类型" v-bind="validateInfos.variantThemes" id="AmazonTaskProductForm-variantThemes" name="variantThemes">
                  <a-input v-model:value="formData.variantThemes" placeholder="" ></a-input>
                </a-form-item>
              </a-col> -->
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
    <BasicTable @register="registerTable" :showTableSetting="false">
      <template #imgs="{ text }">
        <div style="width: 100%;display: flex;flex-wrap: wrap;">
          <TableImg :imgList="text" style="flex: 1;" :size="60" ></TableImg>
        </div>
      </template>
      <template #bodyCell="{ column, record }">
        <div v-if="column.key === 'variantThemes'" color="green">
          {{ record.variantThemes }}{{ record.color?('-'+record.color):'' }}-{{ record.size?('-'+record.size):'' }}
        </div>
      </template>
    </BasicTable>
  </a-spin>
</template>

<script lang="ts" setup>
import { ref, reactive, defineExpose, nextTick, defineProps, computed } from 'vue';
import { useMessage } from '/@/hooks/web/useMessage';
import { getDateByPicker, getValueType } from '/@/utils';
import { saveOrUpdate,querySkuById } from '../AmazonTaskProduct.api';
import { Form } from 'ant-design-vue';
import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
import { useListPage } from '/@/hooks/system/useListPage';
import { BasicTable, BasicColumn,TableImg } from '/@/components/Table';
// import JEditor from '/@/components/Form/src/jeecg/components/JEditor.vue';
const props = defineProps({
  formDisabled: { type: Boolean, default: false },
  formData: { type: Object, default: () => ({})},
  formBpm: { type: Boolean, default: true }
});
const formRef = ref();
const useForm = Form.useForm;
const emit = defineEmits(['register', 'ok']);
const point = computed(()=>{
  return formData.point1 + '\n' + formData.point2 + '\n' + formData.point3 + '\n' + formData.point4 + '\n' + formData.point5
})
const description = computed(()=>{
  let de = formData.description || ''
  return de.replace(/<br>/g,'\n')
})
const formData = reactive<Record<string, any>>({
  id: '',
  title: '',
  productImage:'',
  sku: '',
  brand: '',
  standardPrice: '',
  yunfei: '',
  highPrice: '',
  quantity: '',
  startDate: '',
  currency: '',
  sellerAddress: '',
  taskId: '',

  size:'',
  color:'',
  variantThemes:'',
  cateStr:'',
  asin:'',
  point1:'',
  point2:'',
  point3:'',
  point4:'',
  point5:'',
  purchase:'',
  description:''
  // sellerUrl:'',
  // sellerId:'',
  // sellerName:'',
  // sellerRate:''

});
const { createMessage } = useMessage();
const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
const confirmLoading = ref<boolean>(false);
//表单验证
const validatorRules = reactive({
});
const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });
//日期个性化选择
const fieldPickers = reactive({
});

// 表单禁用
const disabled = computed(()=>{
  if(props.formBpm === true){
    if(props.formData.disabled === false){
      return false;
    }else{
      return true;
    }
  }
  return props.formDisabled;
});


/**
 * 新增
 */
function add() {
  edit({});
}

/**
 * 编辑
 */
function edit(record) {
  nextTick(() => {
    resetFields();
    const tmpData = {};
    Object.keys(formData).forEach((key) => {
      if(record.hasOwnProperty(key)){
        tmpData[key] = record[key]
      }
    })
    //赋值
    Object.assign(formData, tmpData);

    dispathTable()
  });
}
function imageChange(e:string){
  let arr:string[] = e.split(',') || []
  let newArr:Record<string,any> = []
  let index = 1;
  for (const element of arr) {
    newArr.push({
      image_url:element,
      order:index+''
    })
    index++
  }
  formData.productImage = JSON.stringify(newArr)
}
const computedProductImage = computed(()=>{
  let p = (formData.productImage || '') as string
  if(p.length > 0){
    try {
      type productImageType = {
        image_url:string
        order:string | number
      }
      const values:productImageType[] = JSON.parse(p) || []
      let arr:string[] = [];
      for (const s of values) {
        arr.push(s.image_url);
      }
      return arr
    } catch (error) {
      return []
    }
  }
})
/**
 * 提交数据
 */
async function submitForm() {
  try {
    // 触发表单验证
    await validate();
  } catch ({ errorFields }) {
    if (errorFields) {
      const firstField = errorFields[0];
      if (firstField) {
        formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
      }
    }
    return Promise.reject(errorFields);
  }
  confirmLoading.value = true;
  const isUpdate = ref<boolean>(false);
  //时间格式化
  let model = formData;
  if (model.id) {
    isUpdate.value = true;
  }
  //循环数据
  for (let data in model) {
    // 更新个性化日期选择器的值
    model[data] = getDateByPicker(model[data], fieldPickers[data]);
    //如果该数据是数组并且是字符串类型
    if (model[data] instanceof Array) {
      let valueType = getValueType(formRef.value.getProps, data);
      //如果是字符串类型的需要变成以逗号分割的字符串
      if (valueType === 'string') {
        model[data] = model[data].join(',');
      }
    }
  }
  await saveOrUpdate(model, isUpdate.value)
    .then((res) => {
      if (res.success) {
        createMessage.success(res.message);
        emit('ok');
      } else {
        createMessage.warning(res.message);
      }
    })
    .finally(() => {
      confirmLoading.value = false;
    });
}
const columns: BasicColumn[] = [
  {
    title: '变体',
    align: "center",
    dataIndex: 'variantThemes'
  },
  {
    title: '库存',
    align: "center",
    dataIndex: 'quantity'
  },
  {
    title: '最低价',
    align: "center",
    dataIndex: 'standardPrice'
  },
  {
    title: '最高价',
    align: "center",
    dataIndex: 'highPrice'
  },
  {
    title: '图片',
    align: "center",
    dataIndex: 'productImage',
    ellipsis:false,
    width: 400,
    slots: { customRender: 'imgs' },
  },
];
//注册table数据
const { tableContext } = useListPage({
  tableProps: {
    title: '',
    showTableSetting:false,
    api: querySkuById,
    columns,
    canResize:true,//是否可以自适应高度(
    useSearchForm: false,//使用搜索表单
    pagination:true,//分页信息配置，
    showActionColumn:false,//是否显示操作列
    beforeFetch: async (params) => {
      return Object.assign(params, {id:formData.id})
    },
    afterFetch:(res)=>{
      for (const s of res) {
        try {
          const values = JSON.parse(s.productImage) || []
          let arr:string[] = [];
          for (const s of values) {
            arr.push(s.image_url);
          }
          s.productImage = arr;
        } catch (error) {
          console.log(error)
          s.productImage = []
        }
      }
    }
  },
});
const [registerTable,  {reload} ] = tableContext;
function dispathTable(){
  // 通过sku查询变体
  reload();
}
defineExpose({
  add,
  edit,
  submitForm,
});
</script>

<style lang="less" scoped>
.antd-modal-form {
  padding: 14px 20px;
}
</style>
